package com.kinglone.controller;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.json.JsonObject;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.kinglone.model.Upload;
import com.kinglone.service.UploadService;
import com.kinglone.util.DateUtils;
import com.kinglone.util.FileUtils;
import com.kinglone.util.JSONMessageView;
import com.kinglone.util.PropertieUtil;

/**
 * 文件上传demo
 * @author Administrator
 *
 */
@Controller
public class UploadController {

	@Autowired
	private UploadService uploadService;
	
	@RequestMapping("/showUpload.jspx")
	public String showUpload(HttpServletRequest request){
		
		return "showUpload";
	} 
	/**
	 * 使用springmvc上传图片
	 * @param request
	 * @param file
	 * @param taskId
	 * @return
	 * @throws Exception
	 */
	//上传文件会自动绑定到MultipartFile中
    @RequestMapping(value="/upload.html",method=RequestMethod.POST)
    public JSONMessageView upload(HttpServletRequest request,@RequestParam("file") MultipartFile file,@RequestParam("taskId") String taskId) throws Exception {
    	JSONMessageView msg = new JSONMessageView(-1, null, "上传失败!");
       //如果文件不为空，写入上传路径
       if(!file.isEmpty()) {
           //上传文件路径
    	   String basepath=PropertieUtil.getValue("config.properties", "upload_url");
			//相对保存路径									
			String relativePath="/upload/"+DateUtils.format(new Date(), "yyyyMMdd")+"/";
			String holePath=basepath+relativePath;
			System.out.println("完整存储路径："+holePath);
			File f=new File(holePath);
			if(!f.exists()){
				f.mkdirs();
			}
           //上传文件名
           String filename = file.getOriginalFilename();
           String fileType = filename.substring(filename.lastIndexOf(".")+1);   //文件格式 
       		//组成文件实际路径 
        	String truePath=holePath+filename;
        	System.out.println("实际路径为："+truePath);
           //将上传文件保存到一个目标文件当中
        	try {
        		 file.transferTo(new File(truePath));
        		 //String planName = taskService.findPlanNameByTaskId(taskId);
                // importPdfService.saveData(taskId,planName,filename,relativePath+filename,fileType);
			} catch (Exception e) {
				//logger.error("文件保存失败:"+e.getMessage());
				msg.setCode(-1);
	        	msg.setMessage("文件保存失败!");
			}                            
       } else {
    	   msg.setCode(-1);
    	   msg.setMessage("文件不存在!");
    	   return msg;  
       }
       msg.setMessage("文件保存成功!");
       msg.setCode(-1);
       return msg;  
    }
    @RequestMapping(value="/uploadMore.jspx")
    @ResponseBody
    public JSONMessageView uploadMore(HttpServletRequest request,@RequestParam("imgMore") MultipartFile[] imgMore,@RequestParam("taskId") String taskId) throws Exception {
    	JSONMessageView msg = new JSONMessageView(-1, null, "上传失败!");
    	if (imgMore != null && imgMore.length > 0) {
            for (int i = 0; i < imgMore.length; i++) {
                MultipartFile file = imgMore[i];
                // 保存文件
                String imgUrl = FileUtils.uploadFile(request, file);
                String filename = file.getOriginalFilename();
  			    String fileType = filename.substring(filename.lastIndexOf(".")+1);   //文件格式 
  			    			   
            }
        }	
    	msg.setMessage("文件保存成功!");
    	msg.setCode(0);
    	return msg;  
    }
	
	
	
	@RequestMapping("/upload.jspx")
	public JSONMessageView upload(HttpServletRequest request){
		JSONMessageView json = new JSONMessageView(-1, "上传失败!", null);
		try {
			Map<String, String> map = FileUtils.saveMusicByRequest(request, "img");
			for (String key : map.keySet()) {
				json.setCode(0);
				json.setMessage("上传成功!");
				json.setContent(map.get(key));
				System.out.println(json);
			}
			return json;
		} catch (Exception e) {
			e.printStackTrace();
			json.setMessage("上传失败!");
			json.setCode(-1);
			return json;
		}
	}
	@RequestMapping("/saveImport.jspx")
	public JSONMessageView saveImport(HttpServletRequest request){
		JSONMessageView json = new JSONMessageView(-1, "上传失败!", null);
		try {
			String fileName = request.getParameter("fileName");
			String url = request.getParameter("ImpUrl");
			String fileType = request.getParameter("fileType");
			uploadService.saveUpload(fileName,url,fileType);
			JSONObject obj = new JSONObject();
			obj.put("fileName", fileName);
			obj.put("fileType", fileType);
			json.setCode(0);
			json.setMessage("上传成功!");
			json.setContent(obj);
			return json;
		} catch (Exception e) {
			e.printStackTrace();
			json.setMessage("上传失败!");
			json.setCode(-1);
			return json;
		}
	}
	
	@RequestMapping("/findUpload.jspx")
	public ModelAndView findUpload(HttpServletRequest request){
		ModelAndView mv = new ModelAndView("findUpload");
		try {
			List<Upload> uploadList = uploadService.findAll();
			if(uploadList != null){
				mv.addObject("uploadList", uploadList);
			}		
		} catch (Exception e) {
			e.printStackTrace();
		}		
		return mv;
	}
}
